package uutalk.netcloud.talk.base.mqtt.callback;

import com.apkfuns.logutils.LogUtils;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONObject;

import java.io.EOFException;

import uutalk.netcloud.talk.base.mqtt.MQTTManager;
import uutalk.netcloud.talk.base.mqtt.MqttConstant;
import uutalk.netcloud.talk.base.mqtt.event.MQTTActionEvent;
import uutalk.netcloud.talk.base.mqtt.event.MqttMessageEvent;
import uutalk.netcloud.talk.base.mqtt.model.EmqMessage;
import uutalk.netcloud.talk.base.util.thirdpart.EventMamager;

/**
 * Created by hujie on 17/3/30.
 */

public class EventBusMqttCallback implements MqttCallbackExtended {

    @Override
    public void connectionLost(Throwable cause) {
        LogUtils.e("连接丢失" + cause);
        if (cause != null && cause.getCause() != null && cause instanceof MqttException) {
            if (cause.getCause() instanceof EOFException) {
                // todo被T下线
//                Intent intent = new Intent(BootstrapApp.get(), ScanActivity.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent.putExtra("conflict", true);
                //  BootstrapApp.get().startActivity(intent);
                return;
            }
        }
        MQTTManager.getInstance().reConnect();
        EventMamager.getInstance().postEvent(new MQTTActionEvent(MqttConstant.MQTTStatusConstant.CONNECTION_LOST, null, cause));
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        //    MqttBussinessBean bean = JSON.parseObject(message.toString(), MqttBussinessBean.class);
        JSONObject jsonObject = new JSONObject(message.toString());
        System.out.println("获取返回的数据--->" + message.toString());
        if (jsonObject.has("cmd")) {
            EventMamager.getInstance().postEvent(new MqttMessageEvent(new EmqMessage(jsonObject.getString("cmd"), message)));
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

    }

    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        if (reconnect) {
            EventMamager.getInstance().postEvent(new MQTTActionEvent(MqttConstant.MQTTStatusConstant.RECONNNECTION_SUCCESS, null, null));
        }
    }
}
